import { useEffect, useRef, useState } from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import {
    Camera,
    useCameraDevice
} from 'react-native-vision-camera';

import FaceDetection from '@react-native-ml-kit/face-detection';
import ImageResizer from 'react-native-image-resizer';

// 定义截图回调函数类型
interface FaceDetectionProps {
    onFaceDetected?: (imagePath: string) => void;
    detectionInterval?: number;
}

function FaceCheck({ onFaceDetected, detectionInterval = 2000 }: FaceDetectionProps) {
    const [photo, setPhoto] = useState<string | null>(null);
    const [hasDetected, setHasDetected] = useState(false);
    const [faceResult, setFaceResult] = useState<any>(null);
    const [isDetecting, setIsDetecting] = useState(false);
    const camera = useRef<Camera>(null);
    const device = useCameraDevice('front');
    const detectionTimer = useRef<any>(null);

    // 人脸检测功能
    const performDetection = async () => {
        if (isDetecting || hasDetected) return;
        
        try {
            setIsDetecting(true);
            
            if (camera.current) {
                const photo = await camera.current.takePhoto({
                    flash: 'off',
                });
                
                const faces = await FaceDetection.detect(`file://${photo.path}`, {
                    landmarkMode: 'all',
                    contourMode: 'all'
                });
                
                if (faces && faces.length > 0) {
                    const compressed = await ImageResizer.createResizedImage(
                        `file://${photo.path}`,
                        400,
                        400,
                        'JPEG',
                        60
                    );
                    setPhoto(photo.path);
                    setHasDetected(true);
                    setFaceResult(faces);
                    
                    if (onFaceDetected) {
                        onFaceDetected(compressed.uri);
                    }
                    
                    stopDetection();
                }
            }
        } catch (error) {
            console.error('人脸检测错误:', error);
        } finally {
            setIsDetecting(false);
        }
    };

    // 启动检测定时器
    useEffect(() => {
        if (!hasDetected) {
            detectionTimer.current = setInterval(() => {
                performDetection();
            }, detectionInterval);
        }

        return () => {
            if (detectionTimer.current) {
                clearInterval(detectionTimer.current);
                detectionTimer.current = null;
            }
        };
    }, [hasDetected, detectionInterval]);

    // 停止检测
    const stopDetection = () => {
        if (detectionTimer.current) {
            clearInterval(detectionTimer.current);
            detectionTimer.current = null;
        }
        setIsDetecting(false);
    };

    if (!device) {
        return (
          <View style={styles.container}>
              <Text>未检测到摄像头</Text>
          </View>
        );
    }

    return (
      <View style={styles.container}>
          {photo ? (
            <View style={styles.centerContent}>
                <View style={styles.cameraContainer}>
                    <Image
                      source={{uri: `file://${photo}`}}
                      style={StyleSheet.absoluteFill}
                    />
                </View>
                <View style={styles.resultContainer}>
                    <Text style={styles.resultText}>
                        检测到 {faceResult?.length || 0} 张人脸
                    </Text>
                </View>
            </View>
          ) : (
            <>
                <View style={styles.cameraContainer}>
                    <Camera
                      ref={camera}
                      style={StyleSheet.absoluteFill}
                      device={device}
                      isActive={true}
                      photo={true}
                    />
                </View>
                
                <View style={styles.statusContainer}>
                    <Text style={styles.statusText}>
                        {isDetecting ? '正在检测人脸...' : '请将面部对准相机'}
                    </Text>
                </View>
            </>
          )}
      </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#f3f4f6',
        padding: 16,
    },
    centerContent: {
        alignItems: 'center',
    },
    cameraContainer: {
        width: 288,
        height: 288,
        borderRadius: 144,
        overflow: 'hidden',
        borderWidth: 2,
        borderColor: '#3b82f6',
    },
    statusContainer: {
        alignItems: 'center',
        marginTop: 20,
    },
    resultContainer: {
        alignItems: 'center',
        marginTop: 20,
    },
    statusText: {
        color: '#64748b',
        textAlign: 'center',
        fontSize: 16,
        fontWeight: '500',
    },
    resultText: {
        color: '#374151',
        textAlign: 'center',
        fontSize: 18,
        fontWeight: 'bold',
    },
});

export default FaceCheck;